package main

import (
	"encoding/json"
	"log"
	"log-agent/conf"
	"log-agent/etcd"
	"log-agent/tailf"
	"runtime"
	"time"
)

func main() {

	// 1. 启动从etcd拉取配置信息, 解析
	contents, err := etcd.Get(conf.Default.Etcd.LogCollectKey)
	if err != nil {
		log.Fatalf("获取etcd配置信息: %s 失败, 错误信息:%v\n",
			conf.Default.Etcd.LogCollectKey, err)
	}
	var configs []*conf.Pair
	err = json.Unmarshal(contents, &configs)
	if err != nil {
		log.Fatalf("解析etcd日志收集配置信息失败, 错误信息:%v\n",
			err)
	}

	// 2. 创建任务管理, 启动收集任务
	tm := tailf.NewTaskManager()
	for _, config := range configs {
		path, bufferSize := config.Path, config.BufferSize
		tailFileTask, err := tailf.New(path, bufferSize)
		if err != nil {
			log.Printf("创建收集任务 %s 失败, 错误信息:%v\n", err)
			continue
		}
		tm.Add(tailFileTask)
		go tailFileTask.Start()
	}

	// 3. 监听日志收集配置, 处理配置变更
	tk := time.Tick(time.Second * 5)
	configChan := etcd.Watch(conf.Default.LogCollectKey)
	for {
		select {
		case contents := <-configChan:
			var configs []*conf.Pair
			err := json.Unmarshal(contents, &configs)
			if err != nil {
				continue
			}
			// todo 删除和判断有问题, 读取配置
			tm.EvictDeletingTask(configs)
			tm.AddNotExistingTask(configs)
		case <-tk:
			log.Printf("number of goroutine %d, %s",
				runtime.NumGoroutine(), tm)
		}
	}

}
